﻿using Kinlo.MESDocking;
using NPOI.OpenXmlFormats.Spreadsheet;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using UIWindows.GlobalStatics;
using UIWindows.Models.Devices;
using XingLucifer.Devices;
using XingLucifer.IBase.Enums;

namespace UIWindows.Services.PLC_MESHelper
{
    /// <summary>
    /// 后扫码(旋转扫码)
    /// </summary>
    public class AfterScanBarcodeHandler : HelperBase
    {
        PLCBase InjMachine { get; set; }

        MESWinderOutRecordAddRec _mesWinderOutRecord { get; set; }
        public AfterScanBarcodeHandler(
            DeviceInteractiveaddressStatic deviceInteractiveaddressStatic,
            DeviceClientModel deviceModel,
            TemporaryStatic temporaryStatic,
            ParameterStatic parameterStatic,
            DeviceConfigStatic deviceConfigStatic,
            SystemConfigStatic systemConfigStatic,
             HomeStatic homeStatic,
             Action<string, string, string, string, string, long, DateTime, string, string, string, string> log, Action<string, string, string> dialog
            ) : base(deviceInteractiveaddressStatic, deviceModel, temporaryStatic, parameterStatic, deviceConfigStatic, systemConfigStatic, homeStatic, log, dialog)
        {
            InjMachine = deviceModel.PLC;
            _mesWinderOutRecord = new MESWinderOutRecordAddRec(_log, _dialog);
        }

        public override Task Handle()
        {

            Int16 testResult = 2;
            try
            {
                //var dicts = ctx.Container.Get<ConcurrentDictionary<string, object>>();
                //var cfg = ctx.Container.Get<CFG>();
                //InjMachine = (KL21050011Machine)dicts.GetOrAdd("InjMachine", InjMachine);
                //Scanner = (List<KNCScannerMachine>)dicts.GetOrAdd("AfterScaner", Scanner);
                //var Counter = ctx.Container.Get<Counter>();
                //var data = ctx.Container.Get<PlateData>();
                // var trayNos = InjMachine.AftrScanBarcodeIndexs();
                //18线用这个地址
                //var baseAddr = 22900;
                //26线用这个地址
                var baseAddr = 24000;
                var strCode = new List<ushort>();
                for (int i = 0; i < 4; i++)
                {
                    var val = InjMachine.Read($"DM{baseAddr}", 160);
                    strCode.AddRange(val);
                    baseAddr += 160;
                }
                var barcodes1 = new List<string>();
                for (int i = 0; i < 16; i++)
                {
                    var bar = InjMachine.ToString(strCode.Skip(i * 40).Take(40));
                    //18线用这个地址
                    //barcodes1.Insert(0, bar);
                    //26线用这个地址
                    barcodes1.Add(bar);
                }

                RunLog($"【后扫码】{string.Join(";", barcodes1)}");

                DeviceClientModel? device = _deviceConfig.DeviceList.FirstOrDefault(x => x.ServiceName == _deviceModel.ServiceName
         && x.TaskType == TaskTypes.预充后扫码旋转扫码);

                if (device == null)
                {
                    RunLog($"-预充后扫码旋转扫码 触发设备位置找不到，请注意!!!", MessageLevelType.错误);
                    return Task.CompletedTask;
                }
                var barcode = ScanCode(_parameterStatic.RunParameter.Retries_Count_ScanCode, device.Communication, 1);

                if (string.IsNullOrWhiteSpace(barcode))
                {
                    testResult = 2;
                    RunLog($"【预充后扫码旋转扫码】扫码失败");
                }
                else
                {
                    var first = barcodes1.FirstOrDefault().Trim();
                    if (barcode == first)
                    {
                        RunLog( $"【后扫码(旋转扫码)】检验结果OK {barcode}");
                        testResult = 1;
                    }
                    else
                    {
                        testResult = 3;
                        var msg = $"【后扫码(旋转扫码)】检验结果NG {barcode} {first}";
                        RunLog(msg);
                    }
                }
            }
            catch (Exception ex)
            {
                RunLog($"【后扫码】发生异常:{ex}");
            }
            finally
            {
                var r1 = InjMachine.Write<short>("DM1204", new short[] { testResult });
                var r2 = InjMachine.Write<short>("DM1203", new short[] { 1 });
                var r3 = InjMachine.Write<short>("DM1002", new short[] { 0 });
                RunLog($"【后扫码】写结果信号 {testResult} {r1}.{r2}.{r3} {(r1 && r2 && r3 ? "成功" : "失败")}");
            }
            return base.Handle();
        }
    }
}
